package com.jhh.pay.center.cfg;


import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.routing.RouterConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import scala.concurrent.ExecutionContext;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/1
 */
@Component
public class SpringAppContext implements ApplicationContextAware {

    private static volatile ApplicationContext context;

    public static ActorSystem actorSystem() {
        return SpringAppContext.getBean(ActorSystem.class);
    }

    public static ExecutionContext dispatcher() {
        return actorSystem().dispatcher();
    }

    public static ConfigurableApplicationContext getContext() {
        return (ConfigurableApplicationContext) context;
    }

    public static Props props(String actorBeanName) {
        return Props.create(SpringActorProducer.class, context, actorBeanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ActorRef getActor(String beanName, String actorName) {
        final ActorSystem system = actorSystem();
        return system.actorOf(props(beanName), actorName);
    }

    public static ActorRef getActorWithRouter(String name,String actorName, RouterConfig rc) {
        final ActorSystem system = actorSystem();
        return system.actorOf(props(name).withRouter(rc), actorName);
    }

    public static <T> T getBean(Class<T> requestedType) {
        if (context == null) return null;
        return context.getBean(requestedType);
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }
}
